<?php

include ('autoloading_classes.include.php');
/**
* Description of UsersManager
*
* \author Gianmarco Nalin
* \date 27/01/2013
*/

class UsersManager extends Manager {
    
    const CHECK_LOGIN = "SELECT username, password, name, surname, mail FROM users WHERE username = :username AND password = :password;";
    const UPDATE_LAST_LOGIN = "UPDATE users SET last_login = :timestamp WHERE username = :username;";
    const CHECK_COOKIE = "SELECT * FROM cookies WHERE id = :id;";
    const SAVE_COOKIE = "INSERT INTO cookies (id, username, expiry, salt) VALUES (:id, :username, :expiry, :salt);";
    const DELETE_COOKIE = "DELETE FROM cookies WHERE id = :id;";
    const GET_USERNAME_FROM_COOKIE = "SELECT username FROM cookies WHERE id = :id;";
    const GET_USER_INFO_BY_USERNAME = "SELECT username, password, name, surname, mail FROM users WHERE username = :username;";
    const COOKIE_EXPIRATION_TIME = 604800; // / GIORNI
    
    //! Metodo per verificare le credenziali di un utente
    /*!
     * \param username Username dell'utente che vuole effettuare l'accesso.
     * \param password Password dell'utente che vuole effettuare l'accesso.
     * \return Un oggetto di tipo User contentente le informazioni dell'utente se l'utente è registrato, null altrimenti.
     */
    public function login($username, $password) {
        $stmt = $this->connection->prepare(self::CHECK_LOGIN);
        $stmt->execute(array('username' => $username, 'password' => $password));
        $user = null;
        if ($u = $stmt->fetch(PDO::FETCH_ASSOC)) {
            $stmt = $this->connection->prepare(self::UPDATE_LAST_LOGIN);
            $time = new DateTime('now');
            $stmt->execute(array('username' => $username, 'timestamp' => $time->format('Y-m-d H:i:s')));
            $user = new User();
            $user->last_login = $time;
            foreach ($u as $key => $value) {
                $user->{$key} = $value;
            }
        }
        return $user;
    }
    
    public function update_last_login(&$user) {
        $stmt = $this->connection->prepare(self::UPDATE_LAST_LOGIN);
        $time = new DateTime('now');
        $stmt->execute(array('username' => $user->username, 'timestamp' => $time->format('Y-m-d H:i:s')));
        if ($stmt->rowCount() > 0) {
            $user->last_login = $time;
        } else {
            //throw new Exception('Impossibile aggiornare le informazioni dell\'utente... Si prega di riprovare più tardi');
        }
    }
    
    public function save_cookie($username) {
        $salt = md5(mt_rand());
        $token = uniqid($username, TRUE);
        $cookie_id = hash_hmac('sha512', $token, $salt);
        $expiration_time = time() + self::COOKIE_EXPIRATION_TIME;
        $stmt = $this->connection->prepare(self::SAVE_COOKIE);
        $stmt->execute(array(
                'id' => $cookie_id,
                'username' => $username,
                'expiry' => date('Y-m-d H:i:s', $expiration_time),
                'salt' => $salt
            ));
        if($stmt->rowCount() > 0) {
            setcookie('cookie_id', $cookie_id, $expiration_time, '/eventijesolo/', 'www.donboscoland.it');
            setcookie('token', $token, $expiration_time, '/eventijesolo/', 'www.donboscoland.it');
            return TRUE;
        }
        return FALSE;
    }
    
    public function delete_cookie($cookie_id) {
        $stmt = $this->connection->prepare(self::DELETE_COOKIE);
        $stmt->execute(array('id' => $cookie_id));
        if ($stmt->rowCount() > 0) {
            $time = time();
            setcookie('cookie_id', '', $time - 3600, '/eventijesolo/', 'www.donboscoland.it');
            setcookie('token', '', $time - 3600, '/eventijesolo/', 'www.donboscoland.it');
            return TRUE;
        }
        return FALSE;
    }
    
    public function check_cookie($cookie_id, $token) {
        $stmt = $this->connection->prepare(self::CHECK_COOKIE);
        $stmt->execute(array('id' => $cookie_id));
        if ($c = $stmt->fetch(PDO::FETCH_ASSOC)) {
            $expire = new DateTime($c['expiry']);
            $time = new DateTime('now');
            if( $expire > $time ) {
                if ($cookie_id == hash_hmac('sha512', $token, $c['salt'])) {
                    $this->delete_cookie($cookie_id);
                    $this->save_cookie($c['username']);
                    return array('done' => TRUE, 'username' => $c['username']);
                }
                $this->delete_cookie($cookie_id);
                return array('done' => FALSE, 'username' => '');;
            } else {
                $this->delete_cookie($cookie_id);
                return array('done' => FALSE, 'username' => '');;
            }
        } else {
            return array('done' => FALSE, 'username' => '');;
        }
    }
    
    public function get_user_from_cookie_info($cookie_id) {
        $stmt = $this->connection->prepare(self::GET_USERNAME_FROM_COOKIE);
        $stmt->execute(array('id' => $cookie_id));
        if ($r = $stmt->fetch(PDO::FETCH_ASSOC)) {
            return $r['username'];
        } else {
            return null;
        }
    }
}
?>
